package com.gomeplus.commons.quartz.ha;

import com.gomeplus.commons.quartz.business.TaskListenerServerService;
import com.gomeplus.commons.quartz.cache.QuartzPropertiesCache;
import com.gomeplus.commons.quartz.netty.server.NettyServerStartup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

/**
 * Created by zhuml on 2017/12/11.
 */
public abstract class HaService {
    private Logger logger = LoggerFactory.getLogger(HaService.class);
    protected ScheduledExecutorService scheduledExecutorService ;

    private ScheduledExecutorService haExecutorService;
    private TaskListenerServerService taskListenerServerService;

    public void setTaskListenerServerService(TaskListenerServerService taskListenerServerService){
        this.taskListenerServerService = taskListenerServerService;
    }
    private void start() {
        QuartzPropertiesCache.loadingServer();
        NettyServerStartup.getInstance().setTaskListenerServerService(taskListenerServerService);
        NettyServerStartup.getInstance().setRunPort(QuartzPropertiesCache.getServerListenerPort());
        NettyServerStartup.getInstance().start();
        scheduledExecutorService = Executors.newScheduledThreadPool(3,new ThreadFactory() {
            public Thread newThread(Runnable r) {
                return new Thread(r, "HaTaskLogicPool");
            }
        });
        startTask();
    }

    /**
     * 子类实现各种任务
     */
    protected abstract void startTask();

    public void haService(){
        haExecutorService = Executors.newScheduledThreadPool(1,new ThreadFactory() {
            public Thread newThread(Runnable r) {
                return new Thread(r, "haPool");
            }
        });  ;
        haExecutorService.scheduleWithFixedDelay(new haCheckTask(), 0 , 30 , TimeUnit.SECONDS);
    }

    protected abstract boolean haCheck();

    private void stop() {
        NettyServerStartup.getInstance().stop();
        if(null != scheduledExecutorService){
            scheduledExecutorService.shutdown();
        }
    }


    class haCheckTask implements Runnable{

        @Override
        public void run() {
            if(haCheck()){
                start();
                logger.info("start本机master");
            }else {
                stop();
                logger.info("stop本机master");
            }
        }
    }
}
